<?php

namespace app\api\service\pay;


use app\api\model\BoxCollect;
use app\api\service\coupon\MyCoupon;
use app\api\service\game\Point;
use app\common\enum\order\OrderStatus;
use app\common\enum\order\PayStatus;
use app\common\model\lottery\LotteryParticipant;
use app\common\model\lottery\Manage;
use app\common\model\lottery\ReceiveLog;
use app\common\model\Order;
use think\facade\Db;
use think\facade\Log;

class LotteryOrderPay extends PaySuccess
{
    public function onSuccess(array $payment, int $payType)
    {
        Db::startTrans();
        try{
            // 订单更新
            $order = Order::where('order_no', $payment['order_no'])->find();
            $order->pay_status = PayStatus::SUCCESS;
            $order->trans_no = $payment['transaction_id'];
            $order->order_status = OrderStatus::COMPLETED;
            $order->pay_time = time();
            $order->save();
            $lottery_manage = Manage::find($order->activity_id);
            //抽选签号标识更新
            $lottery_participant = LotteryParticipant::where(['lottery_id' => $order->activity_id,'user_id' => $order->user_id])
                ->whereNotNull('win_time')
                ->find();
            Log::channel('wxpay')->info('抽选签号标识更新：'.$lottery_participant->code);
            $lottery_participant->is_receive_reward = 1;
            $lottery_participant->save();
            //增加领取日志
            $receive = ReceiveLog::create([
                'user_id' => $order->user_id,
                'lottery_id' => $order->activity_id,
            ]);
            Log::channel('wxpay')->info('增加领取日志：'.$receive->id ?? '');
            if(!$receive->id){
                return false;
            }
            //同时用户盒柜增加商品
            BoxCollect::create([
                'user_id' => $order->user_id,
                'business' => 'lottery_order',
                'business_id' => $order->order_id,
                'goods_id' => $order->goods_id,
                'goods_source_id' => $order->goods_id,
                'goods_name' => $lottery_manage->name,
                'image_id' => $lottery_manage->cover_id,
                'quantity' => 1,
                'activity_id' => $order->activity_id,
                'activity_name' => $lottery_manage->name,
            ]);
            if($order->coupon_id > 0){
                //核销优惠券
                Log::channel('wxpay')->info('抽选订单核销优惠券：'.$order->coupon_id);
                $res = app(MyCoupon::class)->destruction($order->user_id,$order->coupon_id,$order->order_id,$order->coupon_num);
                if(!$res){
                    return false;
                }
            }
            Db::commit();
            return true;
        }catch (\Exception $e){
            Db::rollBack();
            Log::channel('wxpay')->info('订单号：'.$payment['order_no'].'支付失败');
            Log::channel('wxpay')->info('失败原因：'.$e->getMessage());
            return false;
        }

    }

    public function callSuccess()
    {

    }
}